<template>
<div class="content">
  <div v-if="userData===undefined">
    <h3>拼夕夕--登录</h3>
    <input type="text" placeholder="请输入账号" v-model="account" />
    <input type="password" placeholder="请输入密码" v-model="password" />
    <button @click="login">登录</button>
    <button @click="dialogVisible = true">账号注册</button>
    <button @click="forgetPaw">忘记密码</button>
  </div>
    <!-- 注册用户 -->
    <el-dialog
            title="账号注册"
            :visible.sync="dialogVisible"
            width="50%"
            :append-to-body="true"
            :close-on-click-modal="false">
        <el-form :model="rule" status-icon :rules="rules" ref="rule" label-width="100px" class="demo-ruleForm">
            <el-form-item label="账号" prop="account">
                <el-input v-model="rule.account"/>
            </el-form-item>
            <el-form-item label="昵称" prop="name">
                <el-input v-model="rule.name"/>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="rule.phone"/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="rule.password" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="确认密码" prop="oldpassword">
                <el-input type="password" v-model="rule.oldpassword" autocomplete="off"/>
            </el-form-item>
            <el-form-item>
                <button @click="submitForm('rule')">提交</button>
                <button @click="resetForm('rule')">重置</button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!--忘记密码-->
    <el-dialog title="忘记密码" :visible.sync="dialogFormVisible" :modal='false' :close-on-click-modal="false">
        <el-form :model="formPassword">
            <el-form-item label="账号" :label-width="formLabelWidth">
                <el-col :span="15">
                    <el-input v-model="formPassword.account" autocomplete="off"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth">
                <el-col :span="15">
                    <el-input v-model="formPassword.phone" autocomplete="off"></el-input>
                </el-col>
                <button type="primary" @click="getSmsPhone" :disabled="!BtnStatus">
                    {{BtnStatus?'获取验证码':`${countDownTime}秒后获取`}}
                </button>
            </el-form-item>
            <el-form-item label="验证码" :label-width="formLabelWidth">
                <el-col :span="15">
                    <el-input v-model="formPassword.phoneCode" autocomplete="off"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="新密码" :label-width="formLabelWidth">
                <el-col :span="15">
                    <el-input type="password" v-model="formPassword.password" autocomplete="off"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="确认密码" :label-width="formLabelWidth">
                <el-col :span="15">
                    <el-input type="password" v-model="formPassword.passwords" autocomplete="off"></el-input>
                </el-col>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <button type="submit" @click="forgetPassword">确 定</button>
            <button @click="dialogFormVisible = false">取 消</button>
        </div>
    </el-dialog>
    <!--忘记密码-->

  <div v-if="userData!==undefined">
      <el-tabs v-model="activeName">
          <el-tab-pane label="个人信息" name="first">
              <div style="width: 180px;height: 180px;border:1px solid #000;margin: 0 auto">
                  <el-upload
                      class="avatar-uploader"
                          action="/api/pxx_commodity/commodity/upload"
                          :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                  >
                      <img style="width: 180px;height: 180px" :src="imgUrl" class="avatar">
                  </el-upload>
              </div>
              <div style="width: 500px;height: 500px;margin: 20px auto">
              <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
                  <el-form-item label="名字">
                      <el-input v-model="formLabelAlign.name"/>
                  </el-form-item>
                  <el-form-item label="手机号">
                      <el-input v-model="formLabelAlign.phone"/>
                  </el-form-item>
                  <el-form-item label="邮箱">
                      <el-input v-model="formLabelAlign.email"/>
                  </el-form-item>
              </el-form>
                  <button @click="updateUser">修改</button>
              </div>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="second">
              <div style="width: 500px;height: 500px;margin: 20px auto">
                  <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
                      <el-form-item label="原密码">
                          <el-input type="password" v-model="updateFormPassword.oldPassword"/>
                      </el-form-item>
                      <el-form-item label="新密码">
                          <el-input type="password" v-model="updateFormPassword.newPassword"/>
                      </el-form-item>
                      <el-form-item label="确认密码">
                          <el-input type="password" v-model="updateFormPassword.newPassword1"/>
                      </el-form-item>
                  </el-form>
                  <button @click="updatePassword">修改</button>
              </div>
          </el-tab-pane>
      </el-tabs>
  </div>
</div>



</template>
<script>
  import {isvalidatemobile,isEmail} from "@/util/validate";
  import config from '@/config/config'
  import {setToken,getToken,removeToken} from "@/util/auth";
  export default {
    name: 'UserInfo',
    data () {
        var checkAge = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('不能为空'));
            }
            callback();
        };

        var checkPhone = (rule, value, callback) => {
            var list = isvalidatemobile(value);
            if (list.result === false) {
                return callback(new Error(list.msg));
            }
            callback();
        };

        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.rule.oldpassword !== '') {
                    this.$refs.rule.validateField('oldpassword');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.rule.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
      return {
          updateFormPassword:{
              oldPassword:'',
              newPassword:'',
              newPassword1:''
          },
          labelPosition: 'right',
          formLabelAlign: {
              name: '',
              phone: '',
              email: ''
          },
        activeName: 'first',
        account:'',
        password:'',
        Errpassword:false,
        user:config.user,
        islogin:false,
        flag:false,
        dialogVisible: false,
          dialogFormVisible:false,
          BtnStatus: true,
          countDownTime: 120,
          sendMsgDisabled: false,
        rule: {
            password: '',
            oldpassword: '',
            account: '',
            name:'',
            phone:''
          },
          rules: {
              password: [
                  { validator: validatePass, trigger: 'blur' }
              ],
              oldpassword: [
                  { required: true,validator: validatePass2, trigger: 'blur' }
              ],
              account: [
                  { required: true,validator: checkAge, trigger: 'blur' }
              ],
              name: [
                  { required: true,validator: checkAge, trigger: 'blur' }
              ],
              phone: [
                  { required: true,validator: checkPhone, trigger: 'blur' }
              ],
          },
          formPassword: {
              account: '',
              phone: '',
              phoneCode: '',
              password: '',
              passwords: '',
          },
          formLabelWidth: '80px',
          userData:{},
          imgUrl:''
      };
    },
    mounted() {
          this.loginUser()
      },
    methods:{
        //个人信息与修改密码
        handleAvatarSuccess(res) {
            this.imgUrl = 'http://localhost:7777/'+res.data.url
            this.userData.avatar =res.data.url
        },
        //修改个人信息
        updateUser(){
            var row = this.formLabelAlign
            var list = isvalidatemobile(row.phone);
            if (list.result == false) {
                this.$message.error(list.msg);
                return;
            }
            var email =isEmail(row.email)
            if (!email){
                this.$message.error("邮箱格式不正确!");
                return;
            }
            this.$http({
                method: "post",
                url:"/api/blade-user/update",
                data:JSON.stringify(row),
                headers: {'Content-Type': 'application/json'},
            }).then(res => {
                this.$message({
                    type: "success",
                    message: "修改成功!"
                });
                setToken(row);
            })
        },
        //修改密码
        updatePassword(){
            var userId = this.userData.id
            var oldPassword = this.updateFormPassword.oldPassword
            var newPassword = this.updateFormPassword.newPassword
            var newPassword1 = this.updateFormPassword.newPassword1
            if (oldPassword === '') {
                this.$message.error('请输入密码!');
                return;
            }
            if (newPassword === '') {
                this.$message.error('请输入新密码!');
                return;
            }
            if (newPassword !== newPassword1) {
                this.$message.error('两次输入密码不一致!');
                return;
            }
            var row = {
                id:userId,
                oldPassword:oldPassword,
                newPassword:newPassword,
            }
            this.$http({
                method: "post",
                url:"/api/blade-user/updatePassword",
                data:JSON.stringify(row),
                headers: {'Content-Type': 'application/json'},
            }).then(res => {
                this.$message({
                    type: "success",
                    message: "修改成功,请重新登录!"
                });
                removeToken()
                location.reload();
            }).catch(function(error){
                alert("原密码错误!")
            })

        },
        //获取用户信息
        loginUser(){
          this.userData = getToken()
            if(this.userData===undefined){
              return
          }
            this.userData = JSON.parse(this.userData)
            this.imgUrl = 'http://localhost:7777/'+this.userData.avatar;
            this.formLabelAlign = this.userData
        },
        //发送短信
        getSmsPhone() {
            if (this.formPassword.account === '') {
                this.$message.error('请输入账号!');
                return;
            }
            var phone = this.formPassword.phone;
            var list = isvalidatemobile(phone);
            if (list.result === false) {
                this.$message.error(list.msg);
                return;
            }
            var account = this.formPassword.account;
            this.$http({
                method:"get",
                url:"/api/blade-user/getUserMessage",
                params: {
                    account: account,
                    phone:phone
                }
            }).then(res =>{
                if (JSON.stringify(res.data.data) === '{}'){
                    this.$message.error('该账号不存在!');
                }else {
                    let endMsRes = (new Date()).getTime() + 12000;//2分钟 120000
                    //Setitem 为封装 localStoryge 方法
                    localStorage.setItem('myEndTime', JSON.stringify(endMsRes));
                    this.codeCountDown(endMsRes)
                        this.$http({
                            method:"get",
                            url:"/api/pxx-sms/sms/smsPhone",
                            params: {
                                phone: phone
                            }
                        }).then(res =>{
                            var data = JSON.stringify(res.data);
                            if (JSON.parse(data).success === true) {
                                this.$message({
                                    message: '发送成功!',
                                    type: 'success'
                                });
                            }
                        });
                }
            })
        },
        created() {
            let myEndTime = localStorage.getItem('myEndTime');
            myEndTime && this.codeCountDown(myEndTime)
        },
        codeCountDown(endMsRes) {
            this.BtnStatus = false;
            this.countDownTime = Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
            let time = setTimeout(() => {
                this.countDownTime--
                if (this.countDownTime < 1) {
                    this.BtnStatus = true
                    this.countDownTime = 60
                    localStorage.removeItem('myEndTime')
                    clearTimeout(time)
                } else {
                    this.codeCountDown(endMsRes)
                }
            }, 1000)
        },

        //忘记密码
        forgetPaw() {
            this.dialogFormVisible = true;
            this.created();
        },
        forgetPassword() {
            if (this.formPassword.account === '') {
                this.$message.error('请输入账号!');
                return;
            }
            var phone = this.formPassword.phone;
            var list = isvalidatemobile(phone);
            if (list.result === false) {
                this.$message.error(list.msg);
                return;
            }
            if (this.formPassword.password === '') {
                this.$message.error('请输入密码!');
                return;
            }
            if (this.formPassword.passwords !== this.formPassword.password) {
                this.$message.error('两次输入密码不一致!');
                return;
            }
            var account = this.formPassword.account;
            this.$http({
                method:"get",
                url:"/api/blade-user/getUserMessage",
                params: {
                    account: account,
                    phone:phone
                }
            }).then(res =>{
                if (JSON.stringify(res.data.data) === '{}'){
                    this.$message.error('该账号不存在!');
                }else {
                    const row = {
                        id: res.data.data.id,
                        password: this.$md5(this.formPassword.password),
                        phone: this.formPassword.phone,
                        phoneCode: this.formPassword.phoneCode
                    };
                    this.$http({
                        method: "post",
                        url:"/api/blade-user/getUpdatePassword",
                        data:JSON.stringify(row),
                        headers: {'Content-Type': 'application/json'},
                    }).then(res => {
                        this.$message({
                            type: "success",
                            message: "找回成功!"
                        });
                        this.dialogFormVisible = false;
                        this.formPassword = {};
                    })
                        .catch(function(error){
                            alert("验证码错误!")
                        })

                }
            })
        },
        //注册
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                var row = this.rule
                if (valid) {
                    row.password =this.$md5(this.rule.password)
                    this.$http({
                        method: "post",
                        url:"/api/blade-user/addUser",
                        data:JSON.stringify(row),
                        headers: {'Content-Type': 'application/json'},
                    }).then(res => {
                        this.$message({
                            type: "success",
                            message: "注册成功!"
                        });
                        this.$refs[formName].resetFields();
                        this.dialogVisible = false
                    })
                    .catch(function(error){
                        alert("账号或手机号已被注册")
                    })
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },

        //登录
       login(){
           this.$http({
               method:"get",
               url:"/api/blade-user/login",
               params: {
                   account: this.account,
                   password:this.$md5(this.password)
               }
           }).then(res =>{
               if (JSON.stringify(res.data.data)==='{}'){
                   this.$message({
                       type: "error",
                       message: "账号或密码错误!"
                   });
               }else {
                   this.$message({
                       type: "success",
                       message: "登陆成功!"
                   });
                   this.$router.push({ path: '/'})
               }
               setToken(res.data.data)
           });
      },
    },
  }
</script>
<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
  .Warrning{
    margin: 0 auto;
    text-align: center;
    width: 250px;
    height: 40px;
    line-height: 40px;
    background: rgb(207, 67, 67);
  }
  ul{
    list-style: none;
    padding: 0px;
    margin: 0px;
  }
  ul li{
   height: 200px;

   padding: 20px 0px;
  }
 .content {
    width: 1120px;
    margin-left: auto;
    margin-right: auto;
    padding-top: 20px;
  }
  .base_info{
    display:inline-block;
    text-align: left;
  }
  span {
    display: inline;
    margin-left: 20px;
  }
  .headImg{
    vertical-align: middle;
    width: 200px;
    height: 200px;
  }


</style>
<style scoped>
.login-wrap {
  text-align: center;
}

h3 {
  text-align: center;
}
span {
  text-align: center;
}
input {
  display: block;
  width: 250px;
  height: 40px;
  line-height: 40px;
  margin: 0 auto;
  margin-bottom: 10px;
  outline: none;
  border: 1px solid #888;
  padding: 10px;
  box-sizing: border-box;
}

.NoAccount {
  color: red;
  text-align: center;
}

button {
  display: block;
  width: 250px;
  height: 40px;
  line-height: 40px;
  margin: 0 auto;
  border: none;
  background-color: #41b883;
  color: #fff;
  font-size: 16px;
  margin-bottom: 5px;
}

span {
  cursor: pointer;
}


</style>

